<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加商品按钮 -->
      <el-button type="primary" @click="openAddCategory">添加分类</el-button>
      <!-- 商品列表 -->
      <tree-table
        :data="categories"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-row-hover="false"
        :show-index="true"
        :border="true"
        index-text="#"
      >
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted===false"
            style="color:#67C23A;font-size: 18px;"
          ></i>
          <i class="el-icon-error" v-else style="color:#F56C6C;font-size: 18px;"></i>
        </template>
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level===1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="operate" slot-scope="scope">
          <el-row>
            <el-button
              icon="el-icon-edit"
              type="primary"
              @click="showeditCateName(scope.row.cat_id)"
            >编辑</el-button>
            <el-button icon="el-icon-delete" type="danger" @click="delectCate(scope.row.cat_id)">删除</el-button>
          </el-row>
          <!-- <pre>
            {{scope.row}}
          </pre>-->
        </template>
      </tree-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="query.pagenum"
        :page-size.sync="query.pagesize"
        :page-sizes="[5,10,20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 打开添加分类弹出页 -->
    <el-dialog title="添加分类" :visible.sync="addCategoryVisible" width="30%" @close="addCateDiaClose">
      <el-form
        ref="addCategoryformRef"
        :model="addCategoryform"
        label-width="100px"
        :rules="addCateRules"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCategoryform.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="分类父级目录">
          <el-cascader
            clearable
            v-model="parentChoose"
            :options="parentCateList"
            :props="cascaderconfig"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoryVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategoryButton">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="编辑分类名称"
      :visible.sync="editCategoryVisible"
      width="30%"
      @close="editCateDiaClose"
    >
      <el-form
        ref="editCategoryformRef"
        :model="editCategoryform"
        label-width="100px"
        :rules="addCateRules"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCategoryform.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCategoryVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCategoryButton">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      categories: [],
      //  获取最新商品列表参数
      query: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      //   总的商品列表数
      total: 0,
      //   table表格分列命名规则和渲染内容
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok"
        },
        {
          label: "排序",
          type: "template",
          template: "level"
        },
        {
          label: "操作",
          type: "template",
          template: "operate"
        }
      ],
      //   控制添加分类弹出框
      addCategoryVisible: false,
      editCategoryVisible: false,
      addCategoryform: {
        cat_pid: 0,
        cat_name: "",
        cat_level: 0
      },
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      parentCateList: [],
      parentChoose: [],
      cascaderconfig: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true
      },
      // 现在要操作的行为的id
      editCateId: 0,
      // 编辑元素内容
      editCategoryform: {
        cat_name: ""
      }
    };
  },
  methods: {
    // 获取商品列表
    async getcategories() {
      const { data: res } = await this.$http.get("categories", {
        params: this.query
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品数据失败");
      this.categories = res.data.result;
      this.total = res.data.total;
    },
    handleSizeChange() {
      this.getcategories();
    },
    handleCurrentChange() {
      this.getcategories();
    },
    openAddCategory() {
      this.getParentsCateList();
      this.addCategoryVisible = true;
    },
    async getParentsCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 }
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品数据失败");
      this.parentCateList = res.data;
    },
    // 更换了联机选择器内得数值
    handleChange() {
      console.log(this.parentChoose);
      this.addCategoryform.cat_level = this.parentChoose.length;
      if (this.parentChoose.length === 0) {
        this.addCategoryform.cat_pid = 0;
      } else {
        this.addCategoryform.cat_pid = this.parentChoose[
          this.parentChoose.length - 1
        ];
      }
    },
    // 关闭添加分类按钮
    addCateDiaClose() {
      this.$refs.addCategoryformRef.resetFields();
      this.parentChoose = [];
      this.addCategoryform.cat_pid = 0;
      this.addCategoryform.cat_name = "";
      this.addCategoryform.cat_level = 0;
    },
    // 添加分类功能
    addCategoryButton() {
      this.$refs.addCategoryformRef.validate(async item => {
        if (!item) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCategoryform
        );
        if (res.meta.status !== 201) return this.$message.error("增加分类失败");
        this.$message.success("增加分类成功");
        this.getcategories();
        this.addCategoryVisible = false;
      });
    },
    editCategoryButton() {
      this.$refs.editCategoryformRef.validate(async item => {
        if (!item) return;
        const { data: res } = await this.$http.put(
          `categories/${this.editCateId}`,
          this.editCategoryform
        );
        console.log(res);

        if (res.meta.status !== 200) return this.$message.error("修改分类失败");
        this.$message.success("修改分类成功");
        this.getcategories();
        this.editCategoryVisible = false;
      });
    },
    // 关闭当前编辑分类页面
    editCateDiaClose() {
      this.editCategoryform.cat_name = "";
    },
    // 修改分类名称
    showeditCateName(infoid) {
      this.editCateId = infoid;
      this.editCategoryVisible = true;
    },
    // 删除当前分类
    delectCate(info) {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`categories/` + info);
          console.log(res);
          if (res.meta.status !== 200) {
            return this.$message.error("删除分类失败");
          }
          this.getcategories();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  },
  created() {
    this.getcategories();
  }
};
</script>
<style lang="less" scoped>
.el-cascader{
    width: 100%;
}
</style>